package log

//ContextPool pool of context instances
type ContextPool struct {
	common *HandlerCommon
	pool   chan ContextAllowTar
}

//NewContextPool build a ContextPool instance
func NewContextPool(common *HandlerCommon, size int) *ContextPool {
	p := &ContextPool{
		common: common,
		pool:   make(chan ContextAllowTar, size),
	}
	return p
}

//new create a new instance
func (p *ContextPool) new(level int) ContextAllowTar {
	ctx := NewContextBase(p.common, level)
	ctx.bindRelease(p.release)
	if p.common.UseJSONAssemble {
		ctx.fAssemble = assembleAsJSON
	}
	return ctx
}

//Get get a instance
func (p *ContextPool) Get(level int) ContextAllowTar {
	select {
	case ctx := <-p.pool:
		ctx.Clear()
		ctx.SetLevel(level)
		return ctx
	default:
		return p.new(level)
	}
}

//release push instance back pool
func (p *ContextPool) release(ctx Context) {
	ct, ok := ctx.(ContextAllowTar)
	if !ok {
		return
	}

	select {
	case p.pool <- ct:
	default:
	}
}
